package client.gui;



import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.*;

import client.SendFileToServer;

import java.io.File;


//import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

import messages.MessageAllocateExecuteTesT;
import messages.MessageAllocateExecuteTesTInfo;
import messages.MessageAllocateManualTest;
import messages.MessageAllocateTestId;
import messages.MessageCourse;
import messages.MessageTeacherSubject;

import sharedspace.CalendarComboBox;
import sharedspace.Course;
import sharedspace.DateUtils;
import sharedspace.ExecuteTest;
import sharedspace.Executetestinfo;
import sharedspace.FileHandler;
import sharedspace.ManualTest;
import sharedspace.MyFile;
import sharedspace.Subject;
import sharedspace.Teacher;
import sharedspace.User;

/**
 *	This JPanel Creates a manual test by uploading a file to server
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 */
public class GUI_Create_Manual_Test extends JPanel {


	public JButton btnBack = null;
	private JButton btnCreate;
	protected User user;
	protected Client_GUI MS;
	public JComboBox<String> comboBoxTeacherSubject;
	public JComboBox<String> comboBoxCourse;
	private ArrayList<sharedspace.Subject> s;
	private ArrayList<sharedspace.Course> c;
	protected String subjectChoosen;
	protected String courseChoosen;
	protected String numberOfSubject;
	protected Subject subject;
	private CalendarComboBox popupCal;
	public  byte[] teacherFileByteArray;
	private File fileTeacher;
	private JTextField txtFileName;
	public ManualTest test;
	private String testID="00";
	private Course course;
	private String duration;

	

	public GUI_Create_Manual_Test()
	{
		super();
		this.initializeit();
		
	}
	public GUI_Create_Manual_Test(Client_GUI ms,User user) {
		super();
		this.initializeit();
		this.user = user;
		this.MS=ms;
		this.getTeacherSubject();
	}//end constructor
	
	/**
	 * paints the GUI Screen create comboBoxws to chose subject and course
	 */
	public void initializeit(){
		test = new ManualTest();
		Date d = new Date();
		Calendar cldr = Calendar.getInstance();
		cldr.setTime(d);
		
		JLabel title=new JLabel("Create Manual Test");
		title.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 24));
		title.setBounds(new Rectangle(295, 56, 500, 59));
		title.setForeground(Color.BLUE);
		this.add(title);
		
		btnBack = new JButton();	
		btnBack.setText("Back");
		btnBack.setFont(new Font("Arial", Font.PLAIN, 18));
		btnBack.setBounds(new Rectangle(76, 612, 107, 30));
		btnBack.setVisible(true);

		
		JPanel southPanel = new JPanel();
		add(southPanel, BorderLayout.SOUTH);
		
		JPanel northPanel = new JPanel();
		add(northPanel, BorderLayout.NORTH);
		northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.X_AXIS));

		

		GUI_ImagePanel background =new GUI_ImagePanel(new ImageIcon("images/background1.jpg").getImage());
		background.setLocation(0, 25);
		background.setSize(new Dimension(1246, 800));
		this.setSize(1000, 700);
		this.setLayout(null);
		this.add(btnBack);
		
		this.add(background);
		
		comboBoxCourse= new JComboBox<String>();
		comboBoxCourse.setFont(new Font("Tahoma", Font.BOLD, 14));
		comboBoxCourse.setBounds(415, 199, 120, 24);
		background.add(comboBoxCourse);
		
		JLabel lblCourse = new JLabel("Choose Course:");
		lblCourse.setBounds(405, 136, 164, 42);
		background.add(lblCourse);
		lblCourse.setFont(new Font("Monospaced", Font.BOLD, 18));
		
		comboBoxTeacherSubject= new JComboBox<String>();
		comboBoxTeacherSubject.setFont(new Font("Tahoma", Font.PLAIN, 14));
		comboBoxTeacherSubject.setBounds(159, 199, 120, 24);
		background.add(comboBoxTeacherSubject);
		
			JLabel lblSubject = new JLabel("Choose Subject:");
			lblSubject.setBounds(129, 136, 180, 42);
			background.add(lblSubject);
			lblSubject.setFont(new Font("Monospaced", Font.BOLD, 18));
		
		comboBoxTeacherSubject.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(comboBoxTeacherSubject.getSelectedIndex() > 0){   //if a subject was selected 
					
					 subjectChoosen = (String)comboBoxTeacherSubject.getSelectedItem(); // get the subject that was selected
						for(int i=0; i<s.size();i++){ 					// find the subject in arrayList recieve from message
							if(subjectChoosen==s.get(i).getSubjectName()){
							numberOfSubject=s.get(i).getSubjectID();
							subject=s.get(i);
							}}//end for
					getCourses();      //get course list of the subject
					comboBoxCourse.setEnabled(true);
				}//end if
				else
					comboBoxCourse.setEnabled(false);  // course not selected , don't display the teacher list
			}

		});


		
		txtFileName= new JTextField();
		txtFileName.setBounds(188, 334, 121, 30);
		background.add(txtFileName);
		txtFileName.setColumns(10);
		
		JLabel lblChooseFile = new JLabel("Choose file:");
		lblChooseFile.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblChooseFile.setBounds(94, 335, 84, 24);
		background.add(lblChooseFile);
		
		JButton btnChooseFile = new JButton("Choose File");
		btnChooseFile.setBounds(343, 332, 127, 30);
		background.add(btnChooseFile);
		btnChooseFile.setFont(new Font("Arial", Font.PLAIN, 16));
		
		btnCreate = new JButton("Creat Test");
		btnCreate.setBounds(524, 332, 121, 30);
		background.add(btnCreate);
		btnCreate.setFont(new Font("Arial", Font.PLAIN, 18));
		btnCreate.setVisible(true);
		btnCreate.addActionListener(new ActionListener() {
			/**
			 * This action call the function selectCourse(),and getTeacherSubject()
			 * to select the, from the courses and subject lists
			 */
			public void actionPerformed(ActionEvent e) {
				
				if (comboBoxTeacherSubject.getSelectedIndex()==0)  //subject not selected 
					showMessage("Error, Please Select Subject of Test ", "Input Error", JOptionPane.ERROR_MESSAGE);
				else if (comboBoxCourse.getSelectedIndex()>0){  //course not selected
					//comboBoxCourse.setSelectedIndex(0);
						courseChoosen = (String)comboBoxCourse.getSelectedItem(); // get the subject that was selected
					for(int i=0; i<c.size();i++){ 					// find the subject in arrayList receive from message
						if(courseChoosen==c.get(i).getCourseName()){
							courseChoosen=c.get(i).getCourseID();
							course=c.get(i);
						}}//end for
				    createTheTest(); //Creating a test
				}//end if
				    else showMessage("Error, Please Select the course", "Input Error", JOptionPane.ERROR_MESSAGE);
			}// end actionPerformed		

		});
		
		btnChooseFile.setVisible(true);
		btnChooseFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				openFileDialog();
			}
		});
		
	} //end initializeIt
	/**
	 * saves the manual test in database with File 
	 * duration JOptionPane
	 */
	public void createTheTest(){
		 if(!isValidFileExtension()){
				showMessage("Please Choose only supported file type doc/docx", "Unsupported File Type", JOptionPane.WARNING_MESSAGE);
				return;
		 }
		testID = new String();
		Teacher teacher = new Teacher(user);
		
		
		duration = JOptionPane.showInputDialog("please,Insert Duration of test(minutes):");
		try
		{
		//int duration = Integer.parseInt(string);
			if (cheackDuration(duration))
			{
				testID = new String();
				test.setAuthor(teacher);
				test.setCommentForStudent("manual test");
				test.setCommentForTeacher("manual Test");
				test.setCourse(course);
				test.setTeacherFile(fileTeacher);
				//test.setTeacherFileByteArray(fileByteArray);
				test.setTestID(testID);
				test.setAuthor(teacher);
				//test.setTestDuration(duration);
				test.setSubject(subject);
				
				try {
		    	String path=txtFileName.getText();
		    	int fileLength =(int)fileTeacher.length();
		    	byte[] mybytearray = new byte [(int)fileTeacher.length()];
		        FileInputStream fis = new FileInputStream(fileTeacher);
		        BufferedInputStream bis = new BufferedInputStream(fis);			  	      
				bis.read(mybytearray,0,fileLength);
				test.setPath(path);
				test.setTeacherFile(fileTeacher);
				test.setTeacherFileByteArray(mybytearray);
			} catch (IOException e) {
				showMessage("There was an error uploading the file\n" + e.getMessage(), "Couldn't Upload File", JOptionPane.ERROR_MESSAGE);
		}
				MessageAllocateTestId qTt = new MessageAllocateTestId(subject.getSubjectID(),courseChoosen,test);
				try{
					MS.client.sendToServer(qTt);// get list of teacher subject
					testID = (String)MS.client.GetMessage();
				}catch (Exception e) {System.err.println("Can't get testID");}
				txtFileName.setText("");
					
				if (testID.isEmpty()==false){
					test.setTestID(testID);
					MessageAllocateManualTest aTm =new MessageAllocateManualTest(test,fileTeacher);
					try{
						MS.client.sendToServer(aTm);
						String testIDM = (String)MS.client.GetMessage();
				}catch (Exception e) {System.err.println("Can't get testID");}
				
				}//end if
				showMessage("Your Exam was saved", "Creat Test Manually", JOptionPane.INFORMATION_MESSAGE);
				//MS.setContentPane(MS.tchr);
				}//end if 
				 else JOptionPane.showMessageDialog(null,"Error, invaid number of minutes");
		}catch(NumberFormatException e)
		{
			JOptionPane.showMessageDialog(null, "Invalid Input");
		}
	}//createTheTest
		
	/**
	 * open the file dialog chooser for the teacher to select the test upload file
	 */
	private void openFileDialog(){
		fileTeacher=FileHandler.openFileDialog("Test",txtFileName);
	}// end function openFileDialog
	/**
	 * Check if the selected teacher file is a valid.
	 * for the type of:  {doc, docx}
	 * @return true if contain as extension only one of the above extensions
	 */
	public boolean isValidFileExtension(){
		return FileHandler.isValidFileExtension(fileTeacher);
	}// end function isValidFileExtension
	
	/**
	 * This function display teacher Subject list in combo box 
	 * @param teacherArray - is array list of the teacher subjects
	 */
	public void teacherSubjectComboBox(ArrayList<Subject> teacherSubject) {
		comboBoxTeacherSubject.removeAllItems();  //clear fields 
		if(teacherSubject.size() > 0){   
			comboBoxTeacherSubject.setEnabled(true);
			comboBoxTeacherSubject.addItem("Choose...");
			for (int i=0; i<teacherSubject.size(); i++){
				comboBoxTeacherSubject.addItem(teacherSubject.get(i).getSubjectName());  //display the teacher Subject in combo box
			}
	    }// end if
	    else{
	    	comboBoxTeacherSubject.addItem("Not Available");
	    	comboBoxTeacherSubject.setEnabled(false);
	    }// end else
	}// end function teacherIDComboBox
	
	/**
	 * get the teacher courses to set in comoBox
	 */
	public void getTeacherSubject(){
		MessageTeacherSubject mTs = new MessageTeacherSubject(user);
		try{
			MS.client.sendToServer(mTs);// get list of teacher subject
			
			 s = (ArrayList<Subject>)MS.client.GetMessage();
		
			 teacherSubjectComboBox(s); 
			
			
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} 
		
	}// getTeacherSubject
	
public void showMessage(String message, String title, int messageType) {
	JOptionPane.showMessageDialog(this, message,title,messageType);		
}



/**
 * This function display teacher Subject list in combo box 
 * @param teacherArray - is array list of the teacher subjects
 */
public void teacherCoursesComboBox(ArrayList<Course> teacherCourse) {
	//comboBoxTeacherSubject.removeAllItems();  //clear fields 
	if(teacherCourse.size() > 0){   
		comboBoxCourse.setEnabled(true);
		comboBoxCourse.addItem("Choose...");
		for (int i=0; i<teacherCourse.size(); i++){
			comboBoxCourse.addItem(teacherCourse.get(i).getCourseName());  //display the teacher Subject in combo box
		}//end for
    }// end if
    else{
    	comboBoxCourse.addItem("Not Available");
    	comboBoxCourse.setEnabled(false);
    }// end else
}// end function teacherIDComboBox

/**
 * gets the courses of subject after selection
 */
	private void getCourses() {

	MessageCourse mTc = new MessageCourse(user,numberOfSubject);
	try{
		MS.client.sendToServer(mTc);// get list of teacher subject
		
		 c = (ArrayList<Course>)MS.client.GetMessage();
	
		 teacherCoursesComboBox(c); 
		
		
	} catch (IOException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
		}}

	public File getFileTeacher()
	{
		return fileTeacher;
	}

	public void setFileTeacher(File fileTeacher)
	{
		this.fileTeacher = fileTeacher;
	}
	
	public boolean cheackDuration(String duration)
	{
		try
		{
			int minutes = Integer.parseInt(duration);
			if (minutes>0)
			{
			test.setTestDuration(minutes);
			return true;
			}
			
		}
		catch (NullPointerException e)
		{
			return false;
		}
		catch(NumberFormatException e)
		{
			return false;
		}
		return false;
	}

	public String getDuration() {
		return duration;
	}

	public void setDuration(String duration) {
		this.duration = duration;
	}
	public JButton getBtnCreate() {
		return btnCreate;
	}
	public void setBtnCreate(JButton btnCreate) {
		this.btnCreate = btnCreate;
	}
	public String getTestID() {
		return testID;
	}
}



